#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-22 下午3:43
# @Author  : Tom
# @Site    : 
# @File    : serilizers.py
# @Software: PyCharm
from django.contrib.auth.models import Permission, Group
from rest_framework import serializers
from goods.models import GoodsVisitCount, SKU, SKUSpecification, GoodsCategory, SPU, SpecificationOption, \
    SPUSpecification, Brand, GoodsChannel, GoodsChannelGroup, SKUImage
from orders.models import OrderInfo, OrderGoods
from users.models import User


# --------------------------1.首页：用户数量统计------------------
# 首页用户统计
class GoodsSerializer(serializers.ModelSerializer):
    category = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = GoodsVisitCount
        fields = ('count', 'category')


# --------------------------2.用户管理---------------------------
# 用户管理序列化类
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("id", "username", "mobile", "email", "password")
        extra_kwargs = {
            "password": {
                "write_only": True,
                "max_length": 20,
                "min_length": 8,
            },
            "username": {
                "max_length": 20,
                "min_length": 5,
            }
        }

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)


# --------------------------3.商品管理---------------------------
# 商品管理： sku  用于以下sku序列化器增加数据所用
class SKUSpecificationSerializers(serializers.ModelSerializer):
    class Meta:
        model = SKUSpecification
        fields = ("spec_id", "option_id")


# 商品管理： sku  sku序列化器
class SkuSerializer(serializers.ModelSerializer):
    # 获取序列化的外键STR
    category = serializers.StringRelatedField(read_only=True)
    spu = serializers.StringRelatedField(read_only=True)

    # 获取序列化的外键ID
    category_id = serializers.IntegerField()
    spu_id = serializers.IntegerField()

    # 获取商品的规格选项信息
    # 注意点：如果在这里不设置Only,代表它既可以序列化又可以反序列化，所以在validate_data处必须要剔除来保存sku
    #        如果在这里设置read_only=True， 它不能进行反序列化，所以在validate_data找不到该数据，只能通过self.context['request'].data['specs']来寻找数据
    specs = SKUSpecificationSerializers(many=True)

    class Meta:
        model = SKU
        fields = "__all__"

    # 保存sku的同时，我们必须保存规格选项信息表
    def create(self, validated_data):
        # 1. 获取前端的数据，删除specs,因为sku的表里面没有这个字段
        specs = self.context['request'].data['specs']
        del validated_data["specs"]
        # 2. 保存sku ,  保存规格选项表
        sku = SKU.objects.create(**validated_data)
        # 3. 应该将sku的数据返回回去
        for spec in specs:
            SKUSpecification.objects.create(sku=sku, spec_id=spec['spec_id'], option_id=spec["option_id"])
        return sku

    # 修改当前的商品
    def update(self, instance, validated_data):
        dict1 = self.context["request"].data
        specs = dict1.get("specs")
        instance.caption = validated_data['caption']
        instance.category_id = validated_data['category_id']
        instance.cost_price = validated_data['cost_price']
        instance.is_launched = validated_data['is_launched']
        instance.market_price = validated_data['market_price']
        instance.name = validated_data['name']
        instance.price = validated_data['price']
        instance.spu_id = validated_data['spu_id']
        instance.stock = validated_data['stock']
        instance.save()

        for spec in specs:
            # 当换了商品后，sku的规格信息会减少，所以应该在这里加个判断。
            if spec['spec_id'] == 'undefined':
                return instance
            SKUSpecification.objects.create(sku=instance, spec_id=spec['spec_id'], option_id=spec["option_id"])
        return instance


# 商品管理： sku  三级分类序列化器
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"


# 商品管理： sku 获取spu的序列化器
class SpuSerilizer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = "__all__"


# 商品管理： sku 获取spu的规格选项管理的序列化器，用于下面哪个序列化使用
class SpecificationOptionSerilizer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = "__all__"


# 商品管理： sku 获取spu的规格序列化器
class SpecSerilizer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    options = SpecificationOptionSerilizer(many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"


# 商品管理： spu 获取spu的规格序列化器
class Spu_goodsSerilizer(serializers.ModelSerializer):
    category1 = serializers.StringRelatedField(read_only=True)
    category2 = serializers.StringRelatedField(read_only=True)
    category3 = serializers.StringRelatedField(read_only=True)
    brand = serializers.StringRelatedField(read_only=True)

    category1_id = serializers.IntegerField()
    category2_id = serializers.IntegerField()
    category3_id = serializers.IntegerField()
    brand_id = serializers.IntegerField()

    class Meta:
        model = SPU
        fields = "__all__"


# 商品管理： spu 获取spu的品牌序列化器
class BrandSerilizer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = "__all__"


# 商品管理： spu 获取spu的一级到三级的分类序列化器
class GoodsCategorySerilizer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"


# 商品管理： 规格管理 商品规格管理序列化器
class SpecsSerilizer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    class Meta:
        model = SPUSpecification
        fields = "__all__"


# 商品管理： 规格选项管理 商品规格选项管理序列化器
class SpecsOptionSerilizer(serializers.ModelSerializer):
    spec = serializers.StringRelatedField(read_only=True)
    spec_id = serializers.IntegerField()

    class Meta:
        model = SpecificationOption
        fields = "__all__"


# 商品管理： 频道管理 商品频道管理序列化器
class CategoryGoodsSerilizer(serializers.ModelSerializer):
    group = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)
    group_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    url = serializers.CharField()
    sequence = serializers.CharField()

    class Meta:
        model = GoodsChannel
        fields = "__all__"


# 商品管理： 频道管理 商品频道分组管理序列化器
class GoodsChannelGroupSerilizer(serializers.ModelSerializer):
    class Meta:
        model = GoodsChannelGroup
        fields = "__all__"


# 商品管理： 品牌管理 商品品牌管理序列化器
class GoodsBrandsSerilizer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = "__all__"


# 商品管理： 图片管理 商品图片管理序列化器
class SKUImageSerilizer(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = "__all__"


# 商品管理： 图片管理 商品图片管理序列化器
class SkuSerializer_image(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ("id", "name")


# --------------------------4.订单管理---------------------------
# 订单管理： 获取sku的序列化器，为下面做准备
class SKUOrderSerilizer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ("id", "default_image", "name")


# 订单管理： 获取OrderGoods的序列化器，为下面做准备
class OrderGoodSerilizer(serializers.ModelSerializer):
    sku = SKUOrderSerilizer(read_only=True)
    sku_id = serializers.IntegerField()

    class Meta:
        model = OrderGoods
        fields = ("sku", "sku_id", "count", "price",)


# 订单管理： 获取OrderInfo的序列化器
class OrderSerilizer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True)
    address = serializers.StringRelatedField(read_only=True)
    user_id = serializers.IntegerField()
    address_id = serializers.IntegerField()
    # 获取orderinfor的外键表skus
    skus = OrderGoodSerilizer(many=True, read_only=True)

    class Meta:
        model = OrderInfo
        fields = "__all__"


# 订单管理： 获取OrderInfo的详细信息的序列化器
class OrderDetailSerilizer(serializers.ModelSerializer):
    class Meta:
        model = OrderInfo
        fields = "__all__"


# --------------------------5.系统管理---------------------------
# 权限管理： 获取权限的序列化器
class PermissionPersSerilizer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = "__all__"


# 用户组管理： 获取用户组的序列化器
class Permssioncontent_typesSerilizer(serializers.ModelSerializer):
    class Meta:
        model = Group  # ContentType
        fields = "__all__"


# 管理员管理： 获取管理员的序列化器
class PermissionAdminSerilizer(serializers.ModelSerializer):
    # 接受的数据：
    # id password is_superuser username  mobile email is_staff is_active email-active
    # groups password userperssion  username
    #     this.adminForm.listval = dat.data.groups;
    #     this.adminForm.listval2 = dat.data.user_permissions;

    # user_permissions = serializers.ListField(write_only=True)
    # groups = serializers.ListField(write_only=True)

    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {
            "password": {
                "write_only": True
            }
        }

    # 重写父类方法，增加管理员权限属性
    def create(self, validated_data):
        validated_data["is_staff"] = 1

        password = validated_data['password']
        del validated_data['password']

        # 保存user用户
        user = super().create(validated_data)
        user.set_password(password)
        user.save()

        return user

    def update(self, instance, validated_data):
        user_permission = validated_data['user_permissions']
        groups = validated_data['groups']
        del validated_data['user_permissions']
        del validated_data['groups']

        password = validated_data['password']
        del validated_data['password']

        # 保存user用户
        user = super().update(instance, validated_data)
        user.set_password(password)
        user.save()
